package com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.manager.data.authority.rule;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.MutiModule.common.myPage.MyPageView;
import com.MutiModule.common.mybatis.annotation.MyBatisColumnAnnotation;
import com.MutiModule.common.mybatis.annotation.MyBatisTableAnnotation;
import com.MutiModule.common.twitter.IDGenerator.instance.IdWorkerInstance;
import com.MutiModule.common.utils.DateUtils;
import com.MutiModule.common.utils.StringUtilss;
import com.MutiModule.common.vo.enums.DeleteFlagEnum;
import com.MutiModule.common.vo.enums.sql.operation.SQLOperationModelEnum;
import com.MutiModule.common.vo.mybatis.pagination.Page;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.model.write.ISqlDataAuthorityOperationModelWriteService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.read.ISqlDataAuthorityOperationRuleReadService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.write.ISqlDataAuthorityOperationRuleWriteService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.base.BaseController;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.manager.data.authority.utilss.ScanPackageWithAnnotationUtilss;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.model.SqlDataAuthorityOperationModel;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.rule.SqlDataAuthorityOperationRule;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.view.SqlDataAuthorityOperationView;
import com.alibaba.dubbo.config.annotation.Reference;

/**
 *
 * dubbo 消费者 SqlDataAuthorityOperationRule 模块 读接口
 * 
 * @author alexgaoyh
 *
 */
@Controller
@RequestMapping(value = "manager/data/authority/rule")
public class SqlDataAuthorityOperationRuleController extends BaseController<SqlDataAuthorityOperationRule> {

	@Reference(group = "readService", interfaceName = "com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.read.ISqlDataAuthorityOperationRuleReadService")
	private ISqlDataAuthorityOperationRuleReadService readService;

	@Reference(group = "writeService", interfaceName = "com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.write.ISqlDataAuthorityOperationRuleWriteService")
	private ISqlDataAuthorityOperationRuleWriteService writeService;
	
	@Reference(group = "writeService", interfaceName = "com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.model.write.ISqlDataAuthorityOperationModelWriteService")
	private ISqlDataAuthorityOperationModelWriteService modelWriteService;

	@Override
	public ModelAndView list(ModelAndView model, HttpServletRequest request) {

		super.list(model, request);
		
		model.addObject("sqlDataAuthorityRuleVOList", ScanPackageWithAnnotationUtilss.scanPackageWithAnnotation(null));

		String classPath = request.getParameter("classPath");
		model.addObject("classPath", classPath);
		if(StringUtilss.isNotEmpty(classPath)) {
			MyPageView<SqlDataAuthorityOperationView> pageView = decorateCondition(request, classPath);
			model.addObject("pageView", pageView);
		}
		

		return model;

	}
	
	/**
	 * 封装参数部分
	 * @param request
	 * @return
	 */
	protected MyPageView<SqlDataAuthorityOperationView> decorateCondition(HttpServletRequest request, String classPath) {
		
		String currentPageStr = request.getParameter("currentPage");
		if(StringUtilss.isEmpty(currentPageStr)) {
			currentPageStr = "1";
		}
		
		String recordPerPageStr = request.getParameter("recordPerPage");
		if(StringUtilss.isEmpty(recordPerPageStr)) {
			recordPerPageStr = "10";
		}

		int beginInt = Integer.parseInt(currentPageStr) >=1 ? Integer.parseInt(currentPageStr) : 1;
		
		Page page = new Page((beginInt - 1)*Integer.parseInt(recordPerPageStr), Integer.parseInt(recordPerPageStr));
		
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("page", page);
		map.put("classPath", classPath);
		
		MyPageView<SqlDataAuthorityOperationView> pageView = readService.generateMyPageViewVOWithModel(map);
		
		return pageView;
	}
	
	
	@Override
	public ModelAndView add(ModelAndView model, HttpServletRequest request) {
		
		try {
			super.add(model, request);
			
			String currentPageStr = request.getParameter("currentPage");
			if(StringUtilss.isEmpty(currentPageStr)) {
				currentPageStr = "1";
			}
			String recordPerPageStr = request.getParameter("recordPerPage");
			if(StringUtilss.isEmpty(recordPerPageStr)) {
				recordPerPageStr = "10";
			}
			model.addObject("currentPageStr", currentPageStr);
			model.addObject("recordPerPageStr", recordPerPageStr);
			
			String classPath = request.getParameter("classPath");
			if(StringUtilss.isNotEmpty(classPath)) {
				model.addObject("classPath", classPath);
				Class clazz = Class.forName(classPath);
				
				// 类注解的名称，用来进行名称显示
				Annotation tableAnnotation = clazz.getAnnotation(MyBatisTableAnnotation.class);
				if(tableAnnotation != null && tableAnnotation instanceof MyBatisTableAnnotation) {
					MyBatisTableAnnotation myBatisTableAnnotation = (MyBatisTableAnnotation)tableAnnotation;
					model.addObject("myBatisTableAnnotationRemarks", myBatisTableAnnotation.remarks());
				}
				
				// 类内的字段标示，包含注解的部分才进行显示
				Field[] field = clazz.getDeclaredFields();
				if (field != null && field.length > 0) {
					List<Map<String, String>> _strList = new ArrayList<Map<String, String>>();
					for (Field field2 : field) {
						MyBatisColumnAnnotation annotationColumn = field2.getAnnotation(MyBatisColumnAnnotation.class);
						if (annotationColumn != null) {
							Map<String, String> _map = new HashMap<String, String>();
							_map.put("name", annotationColumn.name());
							_map.put("chineseNote", annotationColumn.chineseNote());
							_strList.add(_map);
						}
					}
					model.addObject("fieldsList", _strList);
				}
				
				// 数据权限规则匹配的操作符部分测试
				model.addObject("sqlDataAuthorityOperationEnums", SQLOperationModelEnum.values());
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return model;
	}
	
	/**
	 * 保存
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/doSaveView")
	public ModelAndView doSaveView(ModelAndView model, HttpServletRequest request, SqlDataAuthorityOperationView entity, RedirectAttributesModelMap modelMap) throws Exception  {
		String viewIdStr = IdWorkerInstance.getIdStr();
		
		SqlDataAuthorityOperationRule rule = (SqlDataAuthorityOperationRule)entity;
		rule.setId(viewIdStr);
		rule.setCreateTime(DateUtils.getGMTBasicTime());
		rule.setDeleteFlag(DeleteFlagEnum.NORMAL);
		
		List<SqlDataAuthorityOperationModel> items = entity.getItems();
		if(items != null && items.size() > 0) {
			for (SqlDataAuthorityOperationModel sqlDataAuthorityOperationModel : items) {
				sqlDataAuthorityOperationModel.setId(IdWorkerInstance.getIdStr());
				sqlDataAuthorityOperationModel.setCreateTime(DateUtils.getGMTBasicTime());
				sqlDataAuthorityOperationModel.setDeleteFlag(DeleteFlagEnum.NORMAL);
				sqlDataAuthorityOperationModel.setDataAuthorityRuleIdFk(viewIdStr);
			}
		}
		
		writeService.insertSqlDataAuthorityOperationView(entity);
		
		String currentPageStr = request.getParameter("currentPageStr");
		String recordPerPageStr = request.getParameter("recordPerPageStr");
		String classPathStr = entity.getClassPath();
		
		modelMap.addAttribute("classPath", classPathStr);
		modelMap.addAttribute("currentPage", currentPageStr);
		modelMap.addAttribute("recordPerPage", recordPerPageStr);
		
		model.setViewName("redirect:list");

		return model;
	}
	
	@RequestMapping(value="/show/{id}")
	public ModelAndView show(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		super.show(id, model, request, modelMap);
		SqlDataAuthorityOperationView operationView = readService.selectEntityWithOperationModelById(id);
		model.addObject("entity", operationView);
		return model;
	}

}
